package structures.tree2;

public class BinaryTreeDemo {
    public static void main(String[] args) {
        DataNode root = new DataNode("name01");
        DataNode name02 = new DataNode("name02");
        DataNode name03 = new DataNode("name03");
        DataNode name04 = new DataNode("name04");
        DataNode name05 = new DataNode("name05");
        DataNode name06 = new DataNode("name06");
        DataNode name07 = new DataNode("name07");

        root.setLeftNode(name02);
        root.setRightNode(name03);
        name02.setLeftNode(name04);
        name02.setRightNode(name05);
        name03.setLeftNode(name06);
        name03.setRightNode(name07);

        BinaryTree binaryTree = new BinaryTree(root);
        binaryTree.preOrder();
        System.out.println("------------------");
        System.out.println(binaryTree.preSearchByName("name08"));
    }
}

class BinaryTree {
    DataNode root;

    public BinaryTree(DataNode root) {
        this.root = root;
    }

    /**
     * 调用前序遍历
     */
    public void preOrder() {
        if (root == null) {
            return;
        }

        root.preOrder();
    }

    /**
     * 调用前序查找
     * @param name
     * @return
     */
    public DataNode preSearchByName(String name) {
        if (root == null) {
            return null;
        }

        return root.preSearchByName(name);
    }

}

class DataNode {
    private String data;
    private DataNode leftNode;
    private DataNode rightNode;

    public DataNode(String data) {
        this.data = data;
    }

    /**
     * 前序遍历
     */
    public void preOrder() {
        System.out.println(this);

        if (this.getLeftNode() != null) {
            this.getLeftNode().preOrder();
        }

        if (this.getRightNode() != null) {
            this.getRightNode().preOrder();
        }
    }

    /**
     * 前序查找
     * @return
     */
    public DataNode preSearchByName(String name) {
        DataNode dataNode = null;

        if (this.getData().equals(name)) {
            dataNode = this;
        }

        if (dataNode == null && this.getLeftNode() != null) {
            dataNode = this.getLeftNode().preSearchByName(name);
        }

        if (dataNode == null && this.getRightNode() != null) {
            dataNode = this.getRightNode().preSearchByName(name);
        }

        return dataNode;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public DataNode getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(DataNode leftNode) {
        this.leftNode = leftNode;
    }

    public DataNode getRightNode() {
        return rightNode;
    }

    public void setRightNode(DataNode rightNode) {
        this.rightNode = rightNode;
    }

    @Override
    public String toString() {
        return "DataNode{" +
                "data='" + data + '\'' +
                '}';
    }
}
